<template>
  <scroll-view
    class="home-list"
    scroll-y
    @scrolltolower="scroll"
    :refresher-triggered="triggered"
    :refresher-threshold="100"
    @refresherrestore="onRestore"
    refresher-enabled
    @refresherrefresh="onRefresh"
    :ower-threshold="0"
  >
    <template v-if="arr && arr.length > 0">
      <u-checkbox-group shape="circle" placement="column" v-model="radioGroup">
        <view class="info-box" v-for="(item, index) in arr" :key="index">
          <u-form
            labelPosition="left"
            :model="arr[index]"
            labelWidth="80"
            labelAlign="left"
            :rules="rules"
            :ref="'uForm' + index"
          >
            <view class="title">
              <view class="radio">
                <u-checkbox :name="index"></u-checkbox>
              </view>
              <text class="txt u-line-1">物料编号</text>
              <view class="tag-box">
                <text class="txt u-line-1"> {{ item.materialCode }}</text>
              </view>
            </view>
            <view class="text-box">
              <text class="label">物料名称:</text>
              <text class="value">{{ item.materialName }}</text>
            </view>
            <view class="text-box">
              <text class="label">规格型号:</text>
              <text class="value">{{ item.materialModel }}</text>
            </view>
            <view class="text-box">
              <text class="label">前班退料总数:</text>
              <text class="value">{{
                item.previousTotal ? item.previousTotal.toFixed(2) : 0
              }}</text>
            </view>
            <view class="text-box">
              <text class="label">当班投料总数:</text>
              <text class="value">{{
                item.onDutyTotal ? Math.floor(item.onDutyTotal*1000)/1000 : 0
              }}</text>
            </view>
            <view class="text-box">
              <text class="label">当班退料总数:</text>
              <text class="value">{{ item.onPreviousDutyTotal || 0 }}</text>
            </view>
            <view class="text-box">
              <text class="label">材料牌号:</text>
              <text class="value">{{ item.materialMark }}</text>
            </view>
            <view class="text-box">
              <text class="label">定额用量:</text>
              <text class="value">{{ item.quotaQuantity }}</text>
            </view>
            <view class="text-box">
              <text class="label">理论用量:</text>
              <text class="value">{{ item.needQuantity }}</text>
            </view>
            <view class="text-box">
              <text class="label">已加料:</text>
              <text class="value">{{ item.added }}</text>
            </view>
            <view class="text-box">
              <text class="label">总投料:</text>
              <text class="value">{{ item.totalFeeding }}</text>
            </view>

            <view class="u-line"></view>

            <view class="input-box">
              <u-form-item label="物料批次:" prop="materialBatch">
                <u-input
                  class="box-input"
                  label
                  v-model="arr[index].materialBatch"
                  placeholder="请填写"
                  clearable
                ></u-input>
              </u-form-item>
            </view>
            <view class="input-box">
              <u-form-item label="材料牌号:" prop="brand">
                <u-input
                  class="box-input"
                  label
                  v-model="arr[index].brand"
                  placeholder="请填写"
                  clearable
                ></u-input>
              </u-form-item>
            </view>
            <view class="input-box">
              <u-form-item label="数量:" required prop="weight">
                <!-- <u-input
                  class="box-input"
                  label
                  type="number"
                  v-model="arr[index].weight"
                  placeholder="请填写"
                  clearable
                ></u-input> -->
                <MyNumber class="box-input" v-model="arr[index].weight" :decimal="3"
                    :halfAdjust="false" :min="0" :max="99999999.999" placeholder="请填写" clearable />
              </u-form-item>
            </view>
            <view class="input-box">
              <u-form-item label="单位:" required prop="unit">
                <u-input
                  class="box-input"
                  label
                  disabled
                  v-model="arr[index].unit"
                  placeholder="请填写"
                  clearable
                ></u-input>
              </u-form-item>
            </view>
            <view class="input-box">
              <template v-if="type == '1'">
                <u-form-item label="出库仓库:" prop="warehouse" required>
                  <uni-data-select
                    v-model="arr[index].warehouse"
                    :localdata="wareHouses"
                    @change="(val, data) => changeWareHouse(data, index)"
                    placeholder="请选择"
                  ></uni-data-select>
                </u-form-item>
              </template>
              <template v-else>
                <u-form-item label="入库仓库:" prop="warehouse">
                  <uni-data-select
                    v-model="arr[index].warehouse"
                    @change="(val, data) => changeWareHouse(data, index)"
                    :localdata="wareHouses"
                    placeholder="请选择"
                  ></uni-data-select>
                </u-form-item>
              </template>
            </view>
            <view class="input-box">
              <u-form-item label="备注:" prop="remarks">
                <u-textarea
                  v-model="arr[index].remarks"
                  placeholder="请输入备注信息"
                ></u-textarea>
              </u-form-item>
            </view>
          </u-form>
        </view>
      </u-checkbox-group>
    </template>
    <template v-else>
      <view class="info-box">
        <Empty />
      </view>
    </template>
    <view class="loading animation-scale-up" v-if="loading"></view>
    <view class="scroll-no-data" v-if="scrollNoData">已拉到最底部</view>
  </scroll-view>
</template>

<script>
import { setPageData } from "@/store/user";
import Empty from "@/components/empty";
import fetch from "@/utils/fetch";
import wmsFetch from "@/utils/wmsFetch";
import { getPageData } from "@/store/user";
import MyDate from "@/components/myDate.vue";
import MyNumber from "@/components/MyNumber";
    
export default {
  components: {
    Empty,
    MyDate,
    MyNumber
  },
  props: {
    type: String,
    data: {
      type: Array,
      default: [],
    },
    wareHouses: {
      type: Array,
      default: [],
    },
    option: {
      type: Object,
      default: () => {},
    },
    scrollNoData: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    data: {
      handler: function (val, oldVal) {
        this.arr = val;
      },
      deep: true,
      immediate: true,
    },
    radioGroup: {
      handler: function (val, oldVal) {
        this.$emit(
          "itemClick",
          val,
          this.arr.filter((item, index) => val.includes(index))
        );
      },
    },
  },
  data() {
    return {
      loading: true,
      noData: false,
      triggered: false,
      localdata: [
        {
          text: "千克",
          value: "千克",
        },
      ],
      arr: [],
      rules: {
        // materialBatch: {
        //   required: true,
        //   message: "请填写单位",
        //   trigger: ["blur", "change"],
        // },
        shift: {
          required: true,
          message: "请填写",
          trigger: ["blur", "change"],
        },
        shiftTime: {
          required: true,
          message: "请填写",
          trigger: ["blur", "change"],
        },
        weight: {
          type: "number",
          required: true,
          message: "请填写",
          trigger: ["blur", "change"],
        },
        unit: {
          required: true,
          message: "请填写",
          trigger: ["blur", "change"],
        },
        warehouse: {
          required: true,
          message: "请填写",
          trigger: ["blur", "change"],
        },
      },
      radioGroup: [],
      model: {},
      searchMaterialCode: "",
    };
  },
  onReady: async function () {},
  onPullDownRefresh() {
    uni.stopPullDownRefresh();
  },
  mounted() {},
  methods: {
    scanCode() {
      // 允许从相机和相册扫码
      const that = this;
      uni.scanCode({
        success: function (res) {
          that.afterScan(res)
        },
      });
    },
	afterScan(scanRes){
		const that = this;
		console.log("条码类型：" + scanRes.scanType);
		console.log("条码内容：" + scanRes.result);
		const info = scanRes.result.split(";") || [];
		if (info[0] === "scene_01") {
		  fetch("get", "/dms/labelPrinting/getLabelInfoBySerial", {
		    tagSerial: info[1],
		  }).then((res1) => {
			  const res=res1.data
		    if (res == null) {
		      uni.$emit("openToast", {
		        type: "error",
		        icon: "error",
		        title: "无标签数据!",
		      });
		      return false;
		    }
		    this.searchMaterialCode = res.materialCode;
		    const index = that.arr.findIndex(
		      (item) => res.materialCode == item.materialCode
		    );
		    if (index !== -1) {
		      that.$set(that.arr, index, {
		        ...that.arr[index],
		        weight: res.residueNumber,
		        materialBatch: res.batchNumber,
		        brand: res.materialMark,
		        tagSerialNumber: info[1],
		      });
			  console.log({
		        ...that.arr[index],
		        weight: res.residueNumber,
		        materialBatch: res.batchNumber,
		        brand: res.materialMark,
		        tagSerialNumber: info[1],
		      })
		      if (!that.radioGroup.includes(index))
		        that.radioGroup.push(index);
		    } else {
		      uni.$emit("openToast", {
		        type: "error",
		        icon: "error",
		        title: "未匹配到物料信息!",
		      });
		    }
		  });
		  // const index = that.arr.findIndex(
		  //   (item) => info[2] == item.materialCode
		  // );
		  // if (index !== -1) {
		  //   that.$set(that.arr, index, {
		  //     ...that.arr[index],
		  //     weight: info[3],
		  //     materialBatch: info[4],
		  //     brand: info.length == 5 ? info[5] : "",
		  //   });
		  //   if (!that.radioGroup.includes(index)) that.radioGroup.push(index);
		} else {
		  wmsFetch("post", "/warehouseService/getStockOutLabel", null, {
		    corpId: "hx",
		    data: {
		      serialNo: info[0],
		    },
		  }).then((wmsData) => {
			  const res=wmsData.data;
		    if (res && res.length !== 0) {
		      const info = res[0];
		      const index = that.arr.findIndex(
		        (item) => info.materialCode == item.materialCode
		      );
		      if (index !== -1) {
		        that.$set(that.arr, index, {
		          ...that.arr[index],
		          weight: info.labelQty || 0,
		          materialBatch: info.batchNo || "",
		          brand: info.batchProp ? info.batchProp.prop_CLPH : "",
		        });
		        if (!that.radioGroup.includes(index))
		          that.radioGroup.push(index);
		      } else {
		        uni.$emit("openToast", {
		          type: "error",
		          icon: "error",
		          title: "未匹配到物料信息!",
		        });
		      }
		    }
		  });
		}
	},
    changeWareHouse(data, index) {
      const that = this;
      that.$set(that.arr, index, {
        ...that.arr[index],
        warehouseId: data.id,
      });
      console.log("changeWareHouse--------", that.arr[index]);
    },
    setAllRadioGroup() {
      this.radioGroup = this.arr.map((item, index) => index);
    },
    setCloseRadioGroup() {
      this.radioGroup = [];
    },
    getValidate() {
      const that = this;
      console.log("that.radioGroup---------", that.radioGroup);
      return Promise.all(
        that.radioGroup.map((item) => {
          console.log('that.$refs["uForm" + index][0]', "uForm" + item);
          return that.$refs["uForm" + item][0].validate();
        })
      );
    },
    getData() {
      const that = this;
      return that.radioGroup.map((item) => {
        return that.arr[item];
      });
    },
    setLoading(val) {
      this.loading = val;
    },
    scroll(e) {
      const that = this;
      if (!that.noData) {
        this.loading = true;
        this.$emit("scrollBottom", (val) => {
          that.noData = val;
          setTimeout(() => {
            this.loading = false;
          }, 400);
        });
      }
    },
    onRefresh() {
      if (this._freshing) return;
      this._freshing = true;
      this.triggered = true;
      this.$emit("onRefresh");
      setTimeout(() => {
        this.triggered = false;
        this._freshing = false;
      }, 1000);
    },
    onRestore() {
      this.triggered = "restore"; // 需要重置
    },
    itemClick(item) {
      if (this.type !== "1") return;
      setPageData(item);
      this.$emit("itemClick", item);
    },
    ok(val) {
      this.$emit("ok", val);
    },
  },
};
</script>

<style lang="scss" scoped>
.home-list {
  min-height: 200rpx;
  margin: 0 20rpx;
  flex: 1;
  overflow: auto;

  .info-box {
    margin: 0 0 20rpx 0;
  }

  .title {
    font-size: 32rpx;
    margin-bottom: 20rpx;
    padding: 0 40rpx 20rpx 40rpx;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    align-items: center;

    .txt {
      flex: 1;
    }

    .tag-box {
      display: flex;
      align-items: center;
    }
  }

  .content-top {
    padding: 40rpx;

    .state {
      color: #f17a0a;
      margin-bottom: 20rpx;
    }
  }

  .text-box {
    display: flex;
    margin-bottom: 20rpx;
    min-height: 38px;

    .label {
      color: #666;
      width: 150rpx;
    }
  }

  .search-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 60rpx;

    .label {
      margin: 0 20rpx;
    }
  }

  .number-davities-box {
    text-align: center;

    .header {
      margin-bottom: 20rpx;
    }

    .item-box {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20rpx;
    }
  }
}
</style>
